<template>
  <div class="DinamicDrawerForm">
    <el-drawer
      ref="drawerRef"
      class="dinamic-drawer"
      v-model="dialogVisible"
      :title="drawerTitle"
      direction="rtl"
    >
      <div class="dinamic-drawer__content">
        <el-scrollbar style="height: calc(100% - 40px)">
          <el-form
            ref="ruleForm"
            :model="form"
            label-position="right"
            :label-width="configObj.formLabelWidth"
          >
            <el-row :gutter="10">
              <template
                v-for="(config, index) in configObj.configs"
                :key="index + 'config'"
              >
                <el-col
                  :sm="config.col"
                  :md="config.col"
                  :lg="config.col"
                  :xl="config.col"
                >
                  <DinamicFormItem
                    :config="config"
                    :form="form"
                  ></DinamicFormItem>
                </el-col>
              </template>
            </el-row>
          </el-form>
        </el-scrollbar>
        <div class="dinamic-drawer__footer">
          <el-button @click="cancelForm">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { reactive, ref, defineExpose, onMounted, provide } from "vue";
import DinamicFormItem from "./DinamicFormItem.vue";
import configObj from "./formConfigs.js";

const emit = defineEmits(["submit"]);

const dialogVisible = ref(false);
const drawerTitle = ref("");
const form = ref({});
const ruleForm = ref();
provide("form", form);

onMounted(() => {
  configObj.configs.forEach((x) => {
    form.value[x.value] = x.isMultiple ? [] : "";
  });
  // console.log("configs", configObj,form.value);
});

const show = (title, isVisible) => {
  dialogVisible.value = isVisible;
  drawerTitle.value = title;
};
const cancelForm = () => {
  dialogVisible.value = false;
};
const confirm = () => {
  ruleForm.value.validate((valid) => {
    if (valid) {
      emit("submit", form.value);
    } else {
      console.log("error submit!!");
      return false;
    }
  });
};
defineExpose({ show });
</script>

<style lang="less" scoped>
.DinamicDrawerForm {
  .dinamic-drawer__content {
    height: 100%;
    .el-form {
      //   height:100%;
    }
    .dinamic-drawer__footer {
      height: 40px;
      display: flex;
      justify-content: end;
      padding-right: 5%;
    }
  }
}
</style>
<style lang="less">
.DinamicDrawerForm {
  .el-drawer__body {
    padding: 0px 0px 20px 0px;
  }
}
</style>
